<?php
namespace App\Http\Controllers\H5;
use App\Http\Controllers\Controller;
use App\Models\NsSupplierGoods;
use App\Models\NsSupplierGoodsHfive;
use App\Models\XuGoodsBrand;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class H5GoodsController  extends Controller
{
    public function uploadImg(Request $request){
        $request->validate(
            ['file' => 'required|image|mimes:jpeg,png,jpg,gif|max:10240'],
            ['file.required' => '请上传图片', 'file.image' => '请上传图片', 'file.mimes' => '只支持jpeg,png,jpg,gif格式', 'file.max' => '最大10MB']
        );
        $image = $request->file('file');
        // 生成安全的文件名
        $fileName = time() . '_' . uniqid() . '.' . $image->extension();
        $path = $image->storeAs('images', $fileName, 'public');
        if($path){
            return successly(['url' => config('app.url').'/storage/' . $path]);
        }
        return fails('上传失败');
    }

    /**
     * H5商品详情（后台）
     */
    public function h5GoodsDetail(Request $request): JsonResponse
    {
        $request->validate(['gid' => 'required|integer|min:1']);
        try {
            $goods = NsSupplierGoods::with('h5contentInfos')
                ->select('id', 'price', 'profit', 'goodsName', 'unitPrice')
                ->findOrFail($request->gid);

            return successly($goods);
        } catch (\Throwable $e) {
            return fails('商品不存在或已下架');
        }
    }
    /**
     * H5商品详情（后台）
     */
    public function profitEdit(Request $request): JsonResponse
    {
        $request->validate(['gid' => 'required|integer|min:1','profit'=>'required']);
        try {
                NsSupplierGoods::query()
                ->where('id',$request->gid )
                ->update(['profit'=>$request -> profit]);
            return successly();
        } catch (\Throwable $e) {
            return fails('商品不存在或已下架');
        }
    }
    /**
     * H5商品编辑
     */
    public function h5GoodsEdit(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'gid' => 'required|integer|min:1',
            'image_top' => 'required|url',
            'image' => 'required|url',
            'content' => 'required|string|min:10',
            'h5_profit' => 'required|numeric|min:0'
        ]);

        try {
            Db::transaction(function () use ($validated) {
                // 更新H5内容
                NsSupplierGoodsHfive::updateOrCreate(
                    ['gid' => $validated['gid']],
                    [
                        'image_top' => $validated['image_top'],
                        'image' => $validated['image'],
                        'content' => $validated['content']
                    ]
                );

                // 更新商品利润
                NsSupplierGoods::where('id', $validated['gid'])
                    ->update(['profit' => $validated['h5_profit'],'h5_show'=>3]);
            });

            return successly();
        } catch (\Throwable $e) {
            dump($e -> getMessage());
            return fails('操作失败，请稍后重试');
        }
    }


    /**
     * H5端商品列表
     */
    public function h5GoodsList(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'goodsName' => 'nullable|string|max:100'
        ]);

        try {
            $query = NsSupplierGoods::with('h5contentInfos')
                ->where('h5_show', 3)
                ->where('release', 1)
                ->select('id', 'price', 'profit', 'goodsName')
                ->orderByDesc('ctime');

            if (!empty($validated['goodsName'])) {
                $query->where('goodsName', 'like', "%{$validated['goodsName']}%");
            }

            $data = $query->paginate(10);

            // 计算展示价格
            $data->getCollection()->transform(function ($item) {
                $item->display_price = number_format($item->price + $item->profit, 4);
                return $item;
            });

            return successly($data);

        } catch (\Throwable $e) {
            return fails('获取失败，请稍后重试');
        }
    }

    /**
     * H5端商品详情（前端）
     */
    public function h5GoodsListDetail(Request $request): JsonResponse
    {
        $request->validate(['gid' => 'required|integer|min:1']);

        try {
            $goods = NsSupplierGoods::with('h5contentInfos')
                ->select('id', 'goodsName', 'price', 'profit')
                ->findOrFail($request->gid);

            // 计算展示价格
            $goods->display_price = number_format($goods->price + $goods->profit, 4);

            return successly($goods);

        } catch (\Throwable $e) {
            return fails('商品不存在或已下架');
        }
    }


    /**
     * H5商品搜索联想
     */
    public function h5GoodsThink(): JsonResponse
    {
        try {
            $goodsNames = NsSupplierGoods::where('h5_show', 3)
                ->where('release',1)
                ->pluck('goodsName');
            return successly($goodsNames);
        } catch (\Throwable $e) {
            return fails('获取失败，请稍后重试');
        }
    }

    /**
     *  商品名称搜索
     */
    public function goodsName(Request $request){
        $request->validate(['gid' => 'required|integer|min:1']);
        try {
            $goods = NsSupplierGoods::select('goodsName')
                ->findOrFail($request->gid);
            return successly($goods);
        } catch (\Throwable $e) {
            return fails('商品不存在或已下架');
        }
    }

    /**
     *  商品一键同步h5
     */
    public function h5GoodsManage(Request $request){
        $validate = $request->validate(['gid' => 'required']);
        try {
            NsSupplierGoods::query()->whereIn('id',explode(',',$validate['gid']))->where('release',1)
                ->update(['h5_show'=>1]);
            return successly();
        } catch (\Throwable $e) {
            return fails('一键失败');
        }
    }

    /**
     *  商品列表
     */
    public function h5GoodsSupplierList(Request $request){
        $filters = [
            'goodsName' => e($request->input('goodsName', '')),
            'brand_id' => $request->input('brand_id'),
            'state' => $request->input('state',''),
            'ids' => $request->input('ids',''),
            'status' => $request->input('status',2)
        ];
        try {
            $query = NsSupplierGoods::query();
            if(!empty($filters['status'])){
                $query->where('h5_show',$filters['status']);
            }else{
                $query->whereIn('h5_show',[1,3]);
            }
                $info = $query->where('release',1)
                ->whereIn('brand_id',XuGoodsBrand::query() -> where('pid',$filters['brand_id']) -> pluck('category_id'))
                     // 应用过滤条件
                ->when($filters['goodsName'], fn($q, $v) => $q->where('goodsName', 'like', "%{$v}%"))
                ->when($filters['state'], fn($q, $v) => $q->where('release', $v))
                ->when($filters['ids'], fn($q, $v) => $q->where('id', $v))
                ->orderByDesc('ctime')
                ->paginate(10);
            return successly($info);
        } catch (\Throwable $e) {
            return fails('暂无数据');
        }
    }
}
